# -*- encoding=UTF-8 -*-
import json
import os
import time
from datetime import datetime
from time import sleep

import requests
import uiautomator2 as u1
from PIL import Image, ImageStat


class monitor:

    def __init__(self, devices_name, packageName):
        self.packageName = packageName
        self.d = u1.connect(devices_name)
        self.d.unlock()
        self.d.press("home")
        self.log_path = time.strftime("Monitor_%Y_%m_%d_%H_%M_%S", time.localtime()) + '.log'

        if not os.path.exists('./pic/'):
            os.makedirs('./pic/')

    def set_up(self):
        self.d.app_stop(self.packageName)
        sleep(1)
        self.d.app_start(self.packageName)

        gotimes = 0
        while True:
            if self.d(text="Home").exists:
                sleep(3)
                break
            else:
                sleep(3)
                gotimes += 1
            if gotimes == 4:
                break

    def test_down(self):
        self.d.app_stop(self.packageName)

    def write_log(self, file_path, str):
        '''
        报告录入工具
        :param str: 字符串
        :return: None
        '''
        if file_path is not None:
            t = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
            with open(file_path, "a") as file:
                file.write(t + " " + str + "\n")
                file.close()

    def resize_image(self, file, width, height, type):
        img = Image.open(file)
        out = img.resize((width, height), Image.Resampling.LANCZOS)  # resize image with high-quality
        out.save(file, type)

    def start_monitor(self, test_num):
        try:
            dingTalk = DingMessage()

            self.d(text='设备1').click(timeout=5)
            time.sleep(10)

            # 截图
            dt = datetime.now().strftime('%Y-%m-%d_%H.%M.%S')
            image = "./pic/" + dt + "_设备1" + ".png"
            self.d.screenshot(image)
            ResizeImage().resize_image(image, 216, 492, 'png')
            dingTalk.test_pass(test_num)

            self.d.press("back")

            self.d(text='设备2').click(timeout=5)
            time.sleep(5)

            # 截图
            dt = datetime.now().strftime('%Y-%m-%d_%H.%M.%S')
            image = "./pic/" + dt + "_设备2" + ".png"
            self.d.screenshot(image)
            ResizeImage().resize_image(image, 216, 492, 'png')
            dingTalk.test_pass(test_num)

            self.d.press("back")

            return True
        except Exception as e:

            print(e)
            dingTalk = DingMessage()
            dingTalk.test_fail(test_num)
            return False

class ResizeImage:
    def resize_image(self, file, width, height, type):
        img = Image.open(file)
        out = img.resize((width, height), Image.Resampling.LANCZOS)  # resize image with high-quality
        out.save(file, type)


class DingMessage:
    def __init__(self):
        self.URL = "https://oapi.dingtalk.com/robot/send?" \
                   "access_token=386892e5ba6523132c7fad8655e47b6f8ec4b63d02d85ff8d697327e2a245f1d"  # Webhook地址

        self.headers = {'Content-Type': 'application/json'}

    def test_fail(self, test_num):
        data_dict = {
            "msgtype": "markdown",
            "markdown": {
                "title": "截图测试异常提示",
                "text": "#### **<font color=#FF0000>第" + str(test_num) + "次测试异常，截图失败" + "**</font>\n\n"
            }
        }
        json_data = json.dumps(data_dict)
        requests.post(self.URL, data=json_data, headers=self.headers, timeout=3)

    def test_pass(self, test_num):
        data_dict = {
            "msgtype": "markdown",
            "markdown": {
                "title": "截图测试通过提示",
                "text": "#### **<font color=#7CFCOO>第" + str(test_num)
                        + "次测试通过**</font>\n\n""> **截图成功:** <font color=#000000>""</font>\n\n"
            }
        }
        json_data = json.dumps(data_dict)
        requests.post(self.URL, data=json_data, headers=self.headers, timeout=3)


if __name__ == '__main__':
    test_time = int(input("请输入测试次数："))
    gap = int(input("等待多久截图一次(单位秒)："))
    ug = monitor(devices_name="0.0.0.0", packageName='com.wyze.gemini')

    count = 1
    while count < test_time + 1:
        ug.set_up()
        if not ug.start_monitor(test_num=count):
            count -= 1
        else:
            count += 1
        time.sleep(gap)
